<template>
  <div>
    <div>“{{ route.query.keyword }}”的相关搜索结果</div>
    <n-tabs
      type="segment"
      :value="type"
      animated
      :on-update:value="handleUpdate"
    >
      <n-tab-pane name="course" tab="课程">
        <loading-group
          :pending="pending"
          :error="error"
          :is-empty="rows.length === 0"
        >
          <template #loading>
            <LoadingCourseSkeleton />
          </template>
          <n-grid :x-gap="20" :cols="4">
            <n-gi v-for="(item, index) in rows" :key="index">
              <CourseList :item="item" />
            </n-gi>
          </n-grid>
          <div class="flex justify-center items-center mt-5 mb-10">
            <n-pagination
              size="large"
              :item-count="total"
              :page="page"
              :page-size="limit"
              :on-update:page="handlePageChange"
            />
          </div>
        </loading-group>
      </n-tab-pane>
      <n-tab-pane name="column" tab="专栏">
        <loading-group
          :pending="pending"
          :error="error"
          :is-empty="rows.length === 0"
        >
          <template #loading>
            <LoadingCourseSkeleton />
          </template>
          <n-grid :x-gap="20" :cols="4">
            <n-gi v-for="(item, index) in rows" :key="index">
              <CourseList :item="item" />
            </n-gi>
          </n-grid>
          <div class="flex justify-center items-center mt-5 mb-10">
            <n-pagination
              size="large"
              :item-count="total"
              :page="page"
              :page-size="limit"
              :on-update:page="handlePageChange"
            />
          </div>
        </loading-group>
      </n-tab-pane>
    </n-tabs>
  </div>
</template>

<script setup>
import { NTabs, NTabPane, NGrid, NGi, NPagination } from "naive-ui";

definePageMeta({
  middleware: ["search"],
});

const route = useRoute();
const title = ref(route.query.keyword);
const type = ref(route.params.type);

useHead({ title });

const { page, limit, pending, error, refresh, rows, total, handlePageChange } =
  await usePage(({ page, limit }) =>
    useSearchListApi(() => {
      return {
        type: type.value,
        page,
        keyword: encodeURIComponent(title.value),
      };
    })
  );

const handleUpdate = (val) => {
  navigateTo({
    params: {
      ...route.params,
      type: val,
      page: 1, // 切换tab重置page
    },
    query: {
      ...route.query,
    },
  });
};

//Query参数刷新页面实现
const stop = watch(
  () => route.query.keyword,
  (newV) => {
    title.value = newV;
    refresh();
  },
  { immediate: true }
);

//页面销毁时解除监听
onBeforeUnmount(() => {
  stop();
});
</script>

<style scoped></style>
